<?php

namespace App\Http\Controllers\App;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\App\BaseController;
use App\Models\User;
use App\Models\Code;
use App\Models\ShopUserCenter;
use App\Models\Shop;
use App\Baqi\Alimns\AliMnsMsg;

include (base_path('extend/Alimsg/Alimsg.php')); 

class UserController extends Controller
{
    /**
     * 注册
     *
     * @return json
     */
    public function reg(Request $request)
    {
        $tel         = $request->input('tel', '');
        $code        = $request->input('code', '');
        $password    = $request->input('password', '');
        $nickname    = $request->input('nickname', '');
        $invite_code = $request->input('invite_code', '');

        //手机验证处理
        if( empty( $tel ) ){

            return self::error('手机号码不可为空');

        }else{

            $userinfo = User::where('user_mobile', $tel)->first();

            if($userinfo) return self::error('手机已被注册');

        }

        //验证码有效期验证
        if( !empty($code) ){

           $check_res = Code::check_code($tel, $code, 'reg');

           if(!$check_res) return self::error('验证码已过期');

        }else{

            return self::error('验证码不可为空');

        }

        //邀请码流程
        $tg_id = 0;
        $shop_id = 0;

        if($invite_code){

            $is_exist = strstr($invite_code, 'X');

            if(!$is_exist) return self::error('无效的邀请码');

            list($pre, $pid) = explode('X', $invite_code);

            if(!$pre || !$pid) return self::error('无效的邀请码');
            //用户邀请码
            if($pre == 'U'){

                $p_info = User::find($pid);

                if($p_info){

                    $tg_id   = $p_info->id;
                    $shop_id = $p_info->shop_id;

                }else{

                    return self::error('无效的邀请码');

                }

            }
            //商户邀请码
            if($pre == 'S'){

                $s_info = Shop::find($pid);

                if($s_info){

                    $shop_id = $s_info->id;

                }else{

                    return self::error('无效的邀请码');

                }

            }

        }

        $user = new User;

        //密码加密处理
        if( !empty($password)){

            $pwd = $user->create_pwd($password);

        }else{

            return self::error('密码不可为空');

        }

        $user->user_name     = $tel;
        $user->user_mobile   = $tel;
        $user->user_pwd      = $pwd;
        $user->login_token   = $user->token($tel);
        $user->login_time    = time();
        $user->user_nickname = $nickname ? $nickname : $user->get_nickname($tel);
        $user->tg_id         = $tg_id;
        $user->shop_id       = $shop_id;
        $user->user_avatar   = $user->get_rand_avatar();

        $user->save();

        if($shop_id){
            // 通过属性获取信息, 如果不存在初始化一个新的实例
            $shop_info = ShopUserCenter::firstOrNew(['shop_id'=>$shop_id, 'user_id'=>$user->id]);
            $shop_info->user_id = $user->id;
            $shop_info->shop_id = $shop_id;
            $shop_info->save();

        }

        $return = User::get_user_info($user);

        return self::json($return, '注册成功');
    }

    /**
     * 发送手机验证码
     *
     * @return json
     */
    public function login(Request $request)
    {
        $tel      = $request->input('tel', '');
        $password = $request->input('password', '');

        //手机验证处理
        if( empty( $tel ) ){

            return self::error('手机号码不可为空');

        }else{

            $userinfo = User::where('user_name', $tel)->first();

        }

        if($userinfo){

            $res = User::check_pwd($password, $userinfo->user_pwd);

            if($res){

                if($userinfo->status == 2) return self::error('该用户已被禁止登录');
                //登录token更新
                $token = User::token($tel);

                User::where('id', $userinfo->id)->update(['login_token'=>$token, 'login_time'=>time()]);

                $userinfo->login_token = $token;

                $return = User::get_user_info($userinfo);

                return self::json($return, '登录成功');

            }else{

                return self::error('用户密码不匹配');

            }

        }else{

            return self::error('该用户未注册');

        }
    }
    
    /**
     *  找回重置密码
     *
     * @return json
     */
    public function find_pwd(Request $request)
    {
        $tel      = $request->input('tel', '');
        $code     = $request->input('code', '');
        $password = $request->input('password', '');

        //手机验证处理
        if( empty( $tel ) ){

            return self::error('手机号码不可为空');

        }else{

            $user = User::where('user_mobile', $tel)->first();

            if(!$user) return self::error('手机未注册');

        }

        //验证码有效期验证
        if( !empty($code) ){

           $check_res = Code::check_code($tel, $code, 'find');

           if(!$check_res) return self::error('验证码错误或过期');

        }else{

            return self::error('验证码不可为空');

        }

        //密码加密处理
        if( !empty($password)){

            $pwd = $user->create_pwd($password);

        }else{

            return self::error('密码不可为空');

        }

        $user->user_pwd      = $pwd;
        $user->login_token   = $user->token($tel);

        $user->save();

        //$return = User::get_user_info($user);

        return self::success('重置密码成功');

    }

    /**
     * 发送手机验证码
     *
     * @return json
     */
    public function sms(Request $request)
    {
        $to   = $request->input('tel', '');
        $type = $request->input('type', '');
        $user_token = $request->header('token');

        if(empty($to)){

            return self::error('手机号码不可为空');

        }

        //验证码保存入库
        $code = (string)mt_rand(1000,9999);

        //验证发送类型 获取不同模版
        switch ($type) {
            case 'login':
                $type = 'login';
                $sql_type = 1;
                break;

            case 'find':
                $type = 'find';
                $sql_type = 2;
                break;

            case 'bind':
                $type = 'bind';
                $sql_type = 3;
                break;

            case 'update':
                $type = 'update';
                $sql_type = 4;
                break;

            case 'update_pay':
                $type = 'update_pay';
                $sql_type = 5;
                break;

            default:
                $type = 'reg';
                $sql_type = 0;
                break;
        }

        $info = Code::where('mobile', $to)->where('type', $sql_type)->value('updated_at');
        
        $time = strtotime($info);

        if( (time()-$time) < 60 ){

            return self::error('请求频繁，60秒后可再次发起请求');

        }

        //存在更新 不存在入库 （每个手机号每种类型只保存一个验证码）
        Code::updateOrCreate(['mobile' => $to, 'type' => $sql_type], ['mobile' => $to, 'code' => $code, 'type' => $sql_type]);
        
        // $smss = new AliMnsMsg;

        // //手机号和验证码必须是string
        // $result = $smss->send_sms($to, $code, $type);

        $smss = new \ Alimsg();

        $result = $smss->sendSms($to, $type, $code);
      
        if($result->Code == 'OK'){

            return self::success('验证码发送成功');

        }else{

            return self::error('验证码发送失败');

        }

    }

    /**
     * 验证验证码
     *
     * @return json
     */
    public function checkcode(Request $request)
    {
        $tel  = $request->input('tel', '');
        $code = $request->input('code', '');
        $type = $request->input('type', '');

        //手机验证处理
        if( empty( $tel ) ){

            return self::error('手机号码不可为空');

        }

        //验证码有效期验证
        if( !empty($code) ){

           $check_res = Code::check_code($tel, $code, $type);

           if(!$check_res) return self::error('验证码已过期');

        }else{

            return self::error('验证码不可为空');

        }

        return self::success('验证成功');

    }

    /**
     * 分享App
     *
     * @return void
     */
    public function share()
    {   
        $user_id = session('user_id');

        if ( !$user_id) {
            return self::error('请先登录');
        }
 
        $data = [
            'url'   =>asset('/regis/newShareRegis.html?'.$user_id),
            'icon'  => 'http://accessorygx.oss-cn-qingdao.aliyuncs.com/logo/Group%2030.png',
            'title' => '格信商城，无微不至',
            'des'   => '给您一个不一样的消费体验',
           
        ];
        
        return self::json($data);
    }

    /**
     * 获取分享注册信息
     *
     * @param Request $request
     * @return void
     */
    public function userData( Request $request )
    {
        $id   = $request->input('id');
        
        $info = User::select('id', 'user_nickname')->find($id);

        $data = [
            'invite_code' => 'UX'. $info['id'],
            'nick_name'   => $info['user_nickname'],
            'id'          => $info['id'],
        ];

       return self::json($data);
    }

    /**
     * 获取加密字符串
     * @return [type] [description]
     */
    public function encryption()
    {
        return self::json(['encryption' => '17c2a3b9cf5e9c4bf7299ab3f2119afc']);
    }


}
